package com.ssh.interceptor;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;

public class MyRegexFieldValidator extends FieldValidatorSupport{
	
    private String expression;
    private boolean caseSensitive = true;
    private boolean trim = true;
    
	public void validate(Object object) throws ValidationException {
        String fieldName = getFieldName();
        Object value = this.getFieldValue(fieldName, object);
        if (value == null || expression == null) {
            return;
        }
        //��Object ת��ΪString���ͣ�ע����Щ���͵�toString�÷�
        String str =value.toString().trim();
        if (str.length() == 0) {
            return;
        }
        Pattern pattern;
        if (isCaseSensitive()) {
            pattern = Pattern.compile(expression);
        } else {
            pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
        }

        String compare = value.toString();
        if ( trim ) {
            compare = compare.trim();
        }
        Matcher matcher = pattern.matcher( compare );

        if (!matcher.matches()) {
            addFieldError(fieldName, object);
        }
	}

	public String getExpression() {
		return expression;
	}

	public void setExpression(String expression) {
		this.expression = expression;
	}

	public boolean isCaseSensitive() {
		return caseSensitive;
	}

	public void setCaseSensitive(boolean caseSensitive) {
		this.caseSensitive = caseSensitive;
	}

	public boolean isTrim() {
		return trim;
	}

	public void setTrim(boolean trim) {
		this.trim = trim;
	}
	
	
}
